<template>
  <a-modal v-model:visible="visible" :footer="null" :title="$t('other.processEdit')" width="100%" wrap-class-name="large-modal" :maskClosable="false" :confirm-loading="loading" :keyboard="false">
    <a-spin :spinning="loading">
      <div class="make-process-modal-container">
        <aside>
          <a-row class="moinfo-box">
            <a-col :span="24" class="mb-8">
              <span>{{$t('hangManage.makeNo')}}：</span>
              <span>{{moInfo.moNo}} </span>
            </a-col>
            <a-col :span="24" class="mb-8">
              <span>{{$t('basicData.styleNo')}}：</span>
              <span>{{moInfo.styleNo}} </span>
            </a-col>
            <a-col :span="24">
              <span>{{$t('basicData.styleNa') }}：</span>
              <span>{{moInfo.styleName}} </span>
            </a-col>
          </a-row>
          <div class="border-top break-all px-20 py-10">
            <b>{{ getFieldText(versionList,processVersionId,'id','name') }}</b>
          </div>
          <div class="version-box">
            <a-form :model="formState" ref="formRef" layout="vertical">
              <a-form-item :label="`${$t('basicData.processVerName')}:`" :rules="processFormRule.name" name="name">
                <a-input v-model:value.trim="formState.name" :maxLength="19" :placeholder="$t('common.pleaseInput')"  />
              </a-form-item>
              <a-form-item :label="`${$t('common.effectDate')}:`" name="effectiveDate" :rules="processFormRule.effectiveDate">
                <a-date-picker v-model:value="formState.effectiveDate" class="full-width" value-format="YYYY-MM-DD" />
              </a-form-item>
              <a-form-item :label="`${$t('basicData.totalTime')}:`" name="totalTime">
                <a-input-number v-model:value="formState.totalTime" disabled class="full-width">
                  <template #addonAfter> {{$t('common.seconds')}} </template>
                </a-input-number>
              </a-form-item>
              <a-form-item :label="`${$t('basicData.totalPrice')}:`" name="totalWages">
                <a-input-number v-model:value="formState.totalWages" disabled class="full-width">
                  <template #addonAfter> {{ $t('other.yuan') }} </template>
                </a-input-number>
              </a-form-item>
            </a-form>
          </div>
        </aside>
        <section>
          <ModalProcessList ref="processListRef" :styleId="moInfo.styleId" :loading="listLoading" :tableData="tableData" @workTimeChange="workTimeChange" @priceChange="priceChange" :processVersionId="processVersionId" :moId="moId" />
        </section>
      </div>
      <div class="modal-operate-btn">
        <a-button class="cancel" @click="onCancel">{{$t('common.cancel')}}</a-button>
        <a-button type="primary" class="confirm" @click=" onConfirm">{{$t('common.ok')}}</a-button>
      </div>
    </a-spin>
  </a-modal>

</template>
<script setup>
import { ref } from 'vue'
import { processFormRule } from './processConfig'
import ModalProcessList from './modalProcessList.vue'
import { message } from 'ant-design-vue'
import { getFieldText } from "@/utils"
import axios from "@/utils/request"
import { cloneDeep, uniqBy } from 'lodash'
import moment from 'moment'
import i18n from '@/locales/index' 
const { t } = i18n.global
const emits = defineEmits(['ok'])
let loading = ref(false)
let visible = ref(false)
let listLoading = ref(false)
let moId = ref()  // 制单id
let moInfo = ref({})
let processVersionId = ref()
let processListRef = ref()
let tableData = ref([])
const formState = ref({})
let formRef = ref()
const versionList = ref([])
const open = async (record) => {
  visible.value = true
  loading.value = true
  try {
    moId.value = record.moId
    processVersionId.value = record.processId
    await getMakeInfo(moId.value)
    await getProcessList(moId.value)
    await getProcessDetails()
    loading.value = false
  } catch {
    loading.value = false
  }
}
const getMakeInfo = async (id) => { // 制单信息
  try {
    const res = await axios.getAction('/api/mo/mo/get', { id })
    moInfo.value = res.data || {}
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    moInfo.value = {}
  }
}
const initPage = (data) => {
  let { name, effectiveDate, moProcDetailVOList } = data
  moProcDetailVOList.forEach(i => {
    i.processPictureUrlList && i.processPictureUrlList.forEach((el) => {
      el.status = 'done'
      el.uid = Math.random()
    })
  })
  tableData.value = moProcDetailVOList
  formState.value = {
    name,
    effectiveDate: moment(effectiveDate ? effectiveDate : moment(new Date()).valueOf()).format('YYYY-MM-DD'),
    totalTime: tableData.value.reduce((prev, next) => { return prev + (next.standardSeconds || 0) }, 0).toFixed(8),
    totalWages: tableData.value.reduce((prev, next) => { return prev + (next.labourCost || 0) }, 0).toFixed(8)
  }
}
const getProcessList = async (id) => {
  try {
    const res = await axios.postAction('/api/mo/mo-proc/list', { moId: id })
    if (res.success) {
      versionList.value = res.data || []
    }
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    versionList.value = []
  }
}
const getProcessDetails = async () => {
  listLoading.value = true
  try {
    const res = await axios.getAction('/api/mo/mo-proc/get', { id: processVersionId.value })
    if (res.success) initPage(res.data)
    listLoading.value = false
  } catch {
    listLoading.value = false
  }
}
const workTimeChange = () => {
  formState.value.totalTime = processListRef.value.dataSource.reduce((prev, next) => { return prev + (next.standardSeconds || 0) }, 0).toFixed(8)
}
const priceChange = () => {
  formState.value.totalWages = processListRef.value.dataSource.reduce((prev, next) => { return prev + (next.labourCost || 0) }, 0).toFixed(8)
}
const queryParams = () => {
  let list = cloneDeep(processListRef.value.dataSource)
  list.forEach(i => {
    i.moId = moId.value
    i.status = i.status   ? 1 : 0
  })
  let { name, effectiveDate } = formState.value
  let params = {
    id: processVersionId.value,
    effectiveDate: moment(effectiveDate).valueOf(),
    name,
    moId: moId.value,
    moProcDetailVOList: list
  }
  return params
}
const onCancel = () => {
  visible.value = false
  formState.value = {}
  tableData.value = []
  moId.value = null
  versionList.value = []
  processVersionId.value = null
}
const onConfirm = async () => {
  try {
    await formRef.value.validateFields()
    await processListRef.value.listFormRef.validateFields()
    let list = processListRef.value.dataSource
    if (list.some(i => i.section != t('components.dg'))) {
      message.warning(t('other.sectionOnlySelectHang'))
      return
    }
    //  唯一值校验
    let isUniq = [ 'processNo', 'name', 'processCode'].some(i => uniqBy(list, i).length != list.length)
    if (isUniq) {
      message.warning('工序号，工序名称，工序代码不唯一!!!!!!!!!')
      return
    }
    loading.value = true
    await sendInfo()
    loading.value = false
  } catch {
    loading.value = false
  }
}
const sendInfo = async () => {
  loading.value = true
  let params = queryParams()
  const res = await axios.postAction('/api/mo/mo-proc/edit', params)
  if (res.success) {
    message.success(res.msg || t('common.doSuccess'))
    emits('ok')
    visible.value = false
  }
}
defineExpose({
  open
})
</script>
